#include "preHeader.h"
#include "DBPSession.h"
#include "DBPSessionHandler.h"
#include "network/ConnectionManager.h"

DBPSession::DBPSession()
: RPCSession("DBPSession", SDBP_RPC_INVOKE_RESP)
{
}

DBPSession::~DBPSession()
{
}

void DBPSession::Init(const std::string& host, const std::string& port)
{
	m_host = host;
	m_port = port;
}

void DBPSession::CheckConnection()
{
	const auto& connPrePtr = GetConnection();
	if (connPrePtr && connPrePtr->IsActive()) {
		return;
	}
	if (!IsStatus(Idle)) {
		return;
	}

	auto connPtr = sConnectionManager.NewConnection(*this);
	connPtr->AsyncConnect(m_host, m_port);

	sSessionManager.AddSession(this);
}

int DBPSession::HandlePacket(INetPacket *pck)
{
	return sDBPSessionHandler.HandlePacket(this, *pck);
}

void DBPSession::OnConnected()
{
	NetPacket req(CDBP_REGISTER);
	PushSendPacket(req);
	RPCSession::OnConnected();
}

void DBPSession::DeleteObject()
{
	ClearRecvPacket();
	ClearShutdownFlag();
	SetStatus(Idle);
}

DBPSession* DBPSession::New(const std::string& host, const std::string& port)
{
	DBPSession* pSession = new DBPSession();
	pSession->Init(host, port);
	return pSession;
}

int DBPSessionHandler::HandleRegisterResp(DBPSession *pSession, INetPacket &pck)
{
	pSession->OnRPCSessionReady();
	return SessionHandleSuccess;
}

RPCError sDBPSessionUpdate4RPCBlockInvoke()
{
	if (sDBPSession.IsActive()) {
		sDBPSession.Update();
		return RPCErrorNone;
	} else {
		return RPCErrorInterrupt;
	}
}
